<template>
    <a-drawer v-model:visible="visible" title="问问deepseek" :width="width >= 600 ? 600 : '100%'" :footer="false"
        class="chat-drawer" @close="handleDrawerClose">
        <!-- 消息展示区域 -->
        <div class="message-container">
            <div v-for="(msg, index) in messages" :key="index" class="message-item"
                :class="{ 'user-msg': msg.role === 'user', 'sys-msg': msg.role === 'system' }">
                <!-- <div class="message-content">{{ msg.content }}</div> -->
                <div class="message-content" v-html="parseMarkdown(msg.content)"></div>
                <div class="message-time">{{ msg.time }}</div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-container">
            <a-textarea v-model:model-value="inputContent" :auto-size="{ minRows: 2, maxRows: 4 }"
                placeholder="输入问题后回车发送" @keydown.enter.prevent="handleSend" class="multiline-input" />
            <a-button type="primary" @click="handleSend" class="send-btn">
                发送
            </a-button>
        </div>
    </a-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useWindowSize } from '@vueuse/core'
import { askDeepseek } from '@/apis/knowledge/knowledge'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'

// 窗口尺寸响应式
const { width } = useWindowSize()

// 输入内容
const inputContent = ref('')

// 消息数据
interface Message {
    role: 'user' | 'system'
    content: string
    time: string
}
const messages = ref<Message[]>([])

// 抽屉控制
const SelectedPhysicalPath = ref('')
const visible = ref(false)

const parseMarkdown = (content: string) => {
    marked.setOptions({
        highlight: (code) => hljs.highlightAuto(code).value
    })
    return marked(content)
}

// 发送消息处理
const handleSend = async () => {
    const content = inputContent.value.trim()
    if (!content) return

    // 添加用户消息
    messages.value.push({
        role: 'user',
        content: content,
        time: new Date().toLocaleTimeString()
    })

    messages.value.push({
        role: 'system',
        content: '思考中……',
        time: new Date().toLocaleTimeString()
    })

    inputContent.value = '' // 清空输入框
    scrollToBottom() // 立即滚动到底部

    try {
        // 构造请求参数（根据实际API要求调整参数结构）
        const params = {
            // filePath: `D:\\Users\\Desktop\\knowledge-base\\file-storage\\${physicalPathId.value.replace(/\//g, '\\')}`,
            filePath: `D:\\Users\\Desktop\\knowledge-base\\file-storage\\`,
            question: content
        }

        // 发起API请求
        const { data } = await askDeepseek(params)

        const message = data.split("</think>\n\n").pop() || data

        messages.value.pop();

        // 添加系统响应消息
        messages.value.push({
            role: 'system',
            content: message || '收到空响应',
            time: new Date().toLocaleTimeString()
        })

    } catch (error) {
        // 错误处理
        messages.value.push({
            role: 'system',
            content: `请求失败：${error.message || '未知错误'}`,
            time: new Date().toLocaleTimeString()
        })
    } finally {
        scrollToBottom() // 确保最终滚动到底部
    }
}

// 自动滚动到底部
const scrollToBottom = () => {
    const container = document.querySelector('.message-container')
    if (container) {
        container.scrollTop = container.scrollHeight
    }
}

// 暴露打开方法
const onOpen = async (physicalPath: string) => {
    SelectedPhysicalPath.value = physicalPath
    visible.value = true
    await nextTick()
    scrollToBottom()
}

const handleDrawerClose = () => {
    messages.value = []
}

defineExpose({ onOpen })
</script>

<style scoped lang="scss">
.chat-drawer {
    display: flex;
    flex-direction: column;

    .message-container {
        flex: 1;
        overflow-y: auto;
        padding: 16px;
        max-height: 70vh;

        .message-item {
            margin: 12px 0;
            max-width: 80%;

            &.user-msg {
                margin-left: auto;
                text-align: right;

                .message-content {
                    background: #e6f7ff;
                    border-radius: 8px 8px 0 8px;
                }
            }

            &.sys-msg {
                margin-right: auto;

                .message-content {
                    background: #f5f5f5;
                    border-radius: 8px 8px 8px 0;
                }
            }

            .message-content {
                display: inline-block;
                padding: 8px 12px;
                word-break: break-word;
                white-space: pre-wrap;
            }

            .message-time {
                font-size: 12px;
                color: #999;
                margin-top: 4px;
            }
        }
    }

    .input-container {
        border-top: 1px solid #e8e8e8;
        padding: 16px;

        .multiline-input {
            width: 100%;
            margin-bottom: 12px;
            resize: vertical;
        }

        .send-btn {
            width: 100%;
        }
    }
}
</style>
